#!/usr/bin/env python3
"""
商品API接口模块
提供商品相关的API调用功能
"""

import json
from typing import Dict, List, Optional, Any
from common.api_client import APIClient
from common.logger import get_logger


class ProductAPI:
    """商品API接口类"""
    
    def __init__(self, base_url: str, api_client: Optional[APIClient] = None):
        """
        初始化商品API
        
        Args:
            base_url: API基础URL
            api_client: API客户端实例，如果为None则创建新实例
        """
        self.base_url = base_url.rstrip('/')
        self.api_client = api_client or APIClient(base_url=self.base_url)
        self.logger = get_logger(__name__)
        
        # API端点
        self.endpoints = {
            'products': '/api/products',
            'product_detail': '/api/products/{product_id}',
            'search': '/api/products/search',
            'categories': '/api/products/categories',
            'category_products': '/api/products/category/{category}',
            'reviews': '/api/products/{product_id}/reviews',
            'add_review': '/api/products/{product_id}/reviews',
            'inventory': '/api/products/{product_id}/inventory'
        }
    
    def get_product_list(self, page: int = 1, limit: int = 10, filters: Optional[Dict] = None) -> Dict[str, Any]:
        """
        获取商品列表
        
        Args:
            page: 页码
            limit: 每页数量
            filters: 过滤条件
                {
                    "category": "商品分类",
                    "min_price": 最低价格,
                    "max_price": 最高价格,
                    "in_stock": 是否有库存
                }
        
        Returns:
            商品列表数据
        """
        self.logger.info(f"获取商品列表 - 页码: {page}, 数量: {limit}")
        
        params = {
            'page': page,
            'limit': limit
        }
        
        if filters:
            params.update(filters)
        
        try:
            response = self.api_client.get(
                self.endpoints['products'],
                params=params
            )
            
            if response.get('success'):
                self.logger.info(f"商品列表获取成功，共 {response.get('data', {}).get('total', 0)} 条记录")
            else:
                self.logger.warning(f"商品列表获取失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"获取商品列表异常: {str(e)}")
            return {
                'success': False,
                'message': f"获取列表失败: {str(e)}",
                'error': str(e)
            }
    
    def get_product_detail(self, product_id: int) -> Dict[str, Any]:
        """
        获取商品详情
        
        Args:
            product_id: 商品ID
        
        Returns:
            商品详情数据
        """
        self.logger.info(f"获取商品详情: {product_id}")
        
        try:
            endpoint = self.endpoints['product_detail'].format(product_id=product_id)
            response = self.api_client.get(endpoint)
            
            if response.get('success'):
                self.logger.info(f"商品详情获取成功: {product_id}")
            else:
                self.logger.warning(f"商品详情获取失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"获取商品详情异常: {str(e)}")
            return {
                'success': False,
                'message': f"获取详情失败: {str(e)}",
                'error': str(e)
            }
    
    def search_products(self, query: str, page: int = 1, limit: int = 10, 
                       filters: Optional[Dict] = None) -> Dict[str, Any]:
        """
        搜索商品
        
        Args:
            query: 搜索关键词
            page: 页码
            limit: 每页数量
            filters: 过滤条件
        
        Returns:
            搜索结果
        """
        self.logger.info(f"搜索商品: {query}")
        
        params = {
            'q': query,
            'page': page,
            'limit': limit
        }
        
        if filters:
            params.update(filters)
        
        try:
            response = self.api_client.get(
                self.endpoints['search'],
                params=params
            )
            
            if response.get('success'):
                self.logger.info(f"商品搜索成功，共 {response.get('data', {}).get('total', 0)} 条结果")
            else:
                self.logger.warning(f"商品搜索失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"商品搜索异常: {str(e)}")
            return {
                'success': False,
                'message': f"搜索失败: {str(e)}",
                'error': str(e)
            }
    
    def get_categories(self) -> Dict[str, Any]:
        """
        获取商品分类列表
        
        Returns:
            分类列表数据
        """
        self.logger.info("获取商品分类列表")
        
        try:
            response = self.api_client.get(self.endpoints['categories'])
            
            if response.get('success'):
                categories = response.get('data', [])
                self.logger.info(f"商品分类获取成功，共 {len(categories)} 个分类")
            else:
                self.logger.warning(f"商品分类获取失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"获取商品分类异常: {str(e)}")
            return {
                'success': False,
                'message': f"获取分类失败: {str(e)}",
                'error': str(e)
            }
    
    def get_products_by_category(self, category: str, page: int = 1, limit: int = 10) -> Dict[str, Any]:
        """
        按分类获取商品
        
        Args:
            category: 分类名称
            page: 页码
            limit: 每页数量
        
        Returns:
            分类商品列表
        """
        self.logger.info(f"获取分类商品: {category}")
        
        try:
            endpoint = self.endpoints['category_products'].format(category=category)
            response = self.api_client.get(endpoint, params={'page': page, 'limit': limit})
            
            if response.get('success'):
                self.logger.info(f"分类商品获取成功: {category}")
            else:
                self.logger.warning(f"分类商品获取失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"获取分类商品异常: {str(e)}")
            return {
                'success': False,
                'message': f"获取分类商品失败: {str(e)}",
                'error': str(e)
            }
    
    def get_product_reviews(self, product_id: int, page: int = 1, limit: int = 10) -> Dict[str, Any]:
        """
        获取商品评价
        
        Args:
            product_id: 商品ID
            page: 页码
            limit: 每页数量
        
        Returns:
            评价列表
        """
        self.logger.info(f"获取商品评价: {product_id}")
        
        try:
            endpoint = self.endpoints['reviews'].format(product_id=product_id)
            response = self.api_client.get(endpoint, params={'page': page, 'limit': limit})
            
            if response.get('success'):
                self.logger.info(f"商品评价获取成功: {product_id}")
            else:
                self.logger.warning(f"商品评价获取失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"获取商品评价异常: {str(e)}")
            return {
                'success': False,
                'message': f"获取评价失败: {str(e)}",
                'error': str(e)
            }
    
    def add_product_review(self, product_id: int, review_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        添加商品评价
        
        Args:
            product_id: 商品ID
            review_data: 评价数据
                {
                    "rating": 评分 (1-5),
                    "comment": "评价内容",
                    "title": "评价标题"
                }
        
        Returns:
            添加结果
        """
        self.logger.info(f"添加商品评价: {product_id}")
        
        try:
            endpoint = self.endpoints['add_review'].format(product_id=product_id)
            response = self.api_client.post(endpoint, data=review_data)
            
            if response.get('success'):
                self.logger.info(f"商品评价添加成功: {product_id}")
            else:
                self.logger.warning(f"商品评价添加失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"添加商品评价异常: {str(e)}")
            return {
                'success': False,
                'message': f"添加评价失败: {str(e)}",
                'error': str(e)
            }
    
    def get_product_inventory(self, product_id: int) -> Dict[str, Any]:
        """
        获取商品库存信息
        
        Args:
            product_id: 商品ID
        
        Returns:
            库存信息
        """
        self.logger.info(f"获取商品库存: {product_id}")
        
        try:
            endpoint = self.endpoints['inventory'].format(product_id=product_id)
            response = self.api_client.get(endpoint)
            
            if response.get('success'):
                self.logger.info(f"商品库存获取成功: {product_id}")
            else:
                self.logger.warning(f"商品库存获取失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"获取商品库存异常: {str(e)}")
            return {
                'success': False,
                'message': f"获取库存失败: {str(e)}",
                'error': str(e)
            }
    
    def update_product_inventory(self, product_id: int, inventory_data: Dict[str, int]) -> Dict[str, Any]:
        """
        更新商品库存
        
        Args:
            product_id: 商品ID
            inventory_data: 库存数据
                {
                    "stock": 库存数量,
                    "reserved": 预留数量
                }
        
        Returns:
            更新结果
        """
        self.logger.info(f"更新商品库存: {product_id}")
        
        try:
            endpoint = self.endpoints['inventory'].format(product_id=product_id)
            response = self.api_client.put(endpoint, data=inventory_data)
            
            if response.get('success'):
                self.logger.info(f"商品库存更新成功: {product_id}")
            else:
                self.logger.warning(f"商品库存更新失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"更新商品库存异常: {str(e)}")
            return {
                'success': False,
                'message': f"更新库存失败: {str(e)}",
                'error': str(e)
            }
    
    def create_product(self, product_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        创建商品
        
        Args:
            product_data: 商品数据
                {
                    "name": "商品名称",
                    "description": "商品描述",
                    "price": 价格,
                    "category": "分类",
                    "stock": 库存数量
                }
        
        Returns:
            创建结果
        """
        self.logger.info(f"创建商品: {product_data.get('name')}")
        
        try:
            response = self.api_client.post(
                self.endpoints['products'],
                data=product_data
            )
            
            if response.get('success'):
                self.logger.info(f"商品创建成功: {product_data.get('name')}")
            else:
                self.logger.warning(f"商品创建失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"创建商品异常: {str(e)}")
            return {
                'success': False,
                'message': f"创建失败: {str(e)}",
                'error': str(e)
            }
    
    def update_product(self, product_id: int, product_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        更新商品信息
        
        Args:
            product_id: 商品ID
            product_data: 商品数据
        
        Returns:
            更新结果
        """
        self.logger.info(f"更新商品信息: {product_id}")
        
        try:
            endpoint = self.endpoints['product_detail'].format(product_id=product_id)
            response = self.api_client.put(endpoint, data=product_data)
            
            if response.get('success'):
                self.logger.info(f"商品信息更新成功: {product_id}")
            else:
                self.logger.warning(f"商品信息更新失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"更新商品信息异常: {str(e)}")
            return {
                'success': False,
                'message': f"更新失败: {str(e)}",
                'error': str(e)
            }
    
    def delete_product(self, product_id: int) -> Dict[str, Any]:
        """
        删除商品
        
        Args:
            product_id: 商品ID
        
        Returns:
            删除结果
        """
        self.logger.info(f"删除商品: {product_id}")
        
        try:
            endpoint = self.endpoints['product_detail'].format(product_id=product_id)
            response = self.api_client.delete(endpoint)
            
            if response.get('success'):
                self.logger.info(f"商品删除成功: {product_id}")
            else:
                self.logger.warning(f"商品删除失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"删除商品异常: {str(e)}")
            return {
                'success': False,
                'message': f"删除失败: {str(e)}",
                'error': str(e)
            }


# 使用示例
if __name__ == "__main__":
    # 创建商品API实例
    product_api = ProductAPI("http://localhost:8000")
    
    # 测试获取商品列表
    result = product_api.get_product_list(page=1, limit=5)
    print("商品列表:", result)
    
    # 测试搜索商品
    result = product_api.search_products("手机", page=1, limit=5)
    print("商品搜索:", result)
    
    # 测试获取分类
    result = product_api.get_categories()
    print("商品分类:", result)
    
    # 测试创建商品
    test_product = {
        "name": "测试商品",
        "description": "这是一个测试商品",
        "price": 99.99,
        "category": "electronics",
        "stock": 100
    }
    
    result = product_api.create_product(test_product)
    print("创建商品:", result)